#!usr/bin/env python
#coding=utf8

import re

from django import template

register = template.Library()

@register.filter(name='rating_star')
def rating_star(value):
    '''
    评分转换为星级(05，10，15....50)
    '''
    if not value:
        return ''
    value = value *10 + 2
    value = (round(value/10)/2) * 10
    return int(value)
    
@register.filter(name='rn_to_br')
def rn_to_br(value):
    '''
    换行符(\r, \n, \r\n)转换为 <br/>
    '''
    return re.sub(r'\r\n|\n|\r','<br/>', value)

@register.filter(name='category_level_indent')
def category_level_indent(value):
    '''
    分类根据节点深度添加树形标识
    '''
    if value <= 0:
        return '-'
    return (value)*'&nbsp;&nbsp;&nbsp;&nbsp;' + '|-- '
    
    
###
#   分页控件
#
#######################
    
@register.inclusion_tag('tags/paginator.html', takes_context=True)
def paginator(context, adjacent_pages=2):
    """
    To be used in conjunction with the object_list generic view.

    Adds pagination context variables for use in displaying first, adjacent and
    last page links in addition to those created by the object_list generic
    view.
    usage: {% paginator 5 %}
    """
    query_string = ''
    request = context.get('request', None)
    if request:
        query_string = request.META.get('QUERY_STRING', '')
        if query_string:
            l = query_string.split('&')
            for q in l:
                if q.find('page=') == 0:
                    l.remove(q)
            query_string = '&'.join(l)

    if not context.get('total_count', None):
        return {'show_pager':False}

    startPage = max(context['page'] - adjacent_pages, 1)
    context['pages'] = max((context['total_count'] + context['page_size'] - 1) / context['page_size'], 1)
    if startPage <= 3: startPage = 1
    endPage = context['page'] + adjacent_pages + 1
    if endPage >= context['pages'] - 1: endPage = context['pages'] + 1
    page_numbers = [n for n in range(startPage, endPage) \
            if n > 0 and n <= context['pages']]
    #page_obj = context['page_obj']
    #paginator = context['paginator']

    return {
        'query_string': query_string,
        'show_pager': True,
        #'page_obj': page_obj,
        #'paginator': paginator,
        #'hits': context['hits'],
        'page_size': context['page_size'],
        'page': context['page'],
        'pages': context['pages'],
        'page_numbers': page_numbers,
        'next': context['page'] + 1,
        'previous': context['page'] - 1,
        'has_next': context['page'] < context['pages'],
        'has_previous': context['page'] > 1,
        'show_first': 1 not in page_numbers,
        'show_last': context['pages'] not in page_numbers,
    }





